package com.fkcai.hansoul.common.util;

import com.fkcai.hansoul.common.constant.UserConstant;
import com.fkcai.hansoul.common.exception.ComFoundException;
import com.fkcai.hansoul.model.entity.User;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 用户操作工具类
 */
public class UserUtil {
	// 初始化敏感词过滤
	private static final SensitiveWordBs WORD_BS = SensitiveWordBs.newInstance()
			.ignoreCase(true)   // 忽略大小写
			.init();            // 初始化默认敏感词库
	
	
	/**
	 * 过滤用户名敏感词
	 *
	 * @param username 用户名
	 */
	public static void filterSensitiveWords(String username) {
		if (WORD_BS.contains(username)) {
			throw new ComFoundException(ResultCode.USER_SENSITIVE_WORD);
		}
	}
	
	
	/**
	 *  替换敏感词为 **
	 * @param text 文本
	 * @return  过滤内容
	 */
	public static String replaceSensitiveWords(String text) {
		return WORD_BS.replace(text);
	}
	
	
	/**
	 * 根据生日修改年龄
	 *
	 * @param birthday 生日
	 * @return 年龄
	 */
	public static int getCalculateAge (LocalDate birthday) {
		if (birthday == null) {
			throw new ComFoundException(ResultCode.USER_BIRTHDAY_NOT_NULL);
		}
		
		if (birthday.isAfter(LocalDate.now())) {
			throw new ComFoundException(ResultCode.USER_BIRTHDAY_NOT_FUTURE);
		}
		
		return (int) ChronoUnit.YEARS.between(birthday, LocalDate.now());
	}
	
	
	/**
	 * 检查是否在 7 天内修改过
	 * @param lastUsernameUpdateTime 上次修改用户名的时间
	 */
	public static void checkUsernameUpdateInterval(LocalDateTime lastUsernameUpdateTime) {
		if (lastUsernameUpdateTime == null) {
			return;
		}
		
		LocalDateTime now = LocalDateTime.now();
		
		long between = ChronoUnit.DAYS.between(
				lastUsernameUpdateTime.toLocalDate(),
				now.toLocalDate()
		);
		
		if (between < 7) {
			throw new ComFoundException(ResultCode.USERNAME_UPDATE_INTERVAL_NOT_EXCEEDED);
		}
	}
	
	
}
